package com.kcl.dfss;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.apache.http.client.RedirectException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.kcl.dfss.http.ServerConnection;
import com.kcl.dfss.utils.AppUtils;

public class RegisterActivity extends Activity implements OnClickListener{

	private LinearLayout layout_register_back;
	private EditText reg_personal,reg_phone,reg_code,reg_pwd;
	private Button btn_getcode,btn_register;
	private CheckBox reg_check;
	private TextView user_protocol;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_register);
		
		layout_register_back = (LinearLayout) findViewById(R.id.layout_register_back);
		reg_personal = (EditText) findViewById(R.id.reg_personal);
		reg_phone = (EditText) findViewById(R.id.reg_phone);
		reg_code = (EditText) findViewById(R.id.reg_code);
		reg_pwd = (EditText) findViewById(R.id.reg_pwd);
		btn_getcode = (Button) findViewById(R.id.btn_getcode);
		btn_register = (Button) findViewById(R.id.btn_register);
		reg_check = (CheckBox) findViewById(R.id.reg_check);
		user_protocol = (TextView) findViewById(R.id.user_protocol);
		
		layout_register_back.setOnClickListener(this);
		btn_getcode.setOnClickListener(this);
		btn_register.setOnClickListener(this);
		user_protocol.setOnClickListener(this);
		btn_register.setEnabled(false);
		
		reg_check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					btn_register.setEnabled(true);
					btn_register.setBackgroundResource(R.drawable.changepwd_selector);
				}else{
					btn_register.setEnabled(false);
					btn_register.setBackgroundResource(R.drawable.changepwd_noclick);
				}
			}
		});
		
	}
	
	/*public static boolean stringFileter(String str){
		boolean b = false;
		String regEx = "[0-9]{11}";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		b = m.matches();
		return b;
	}*/
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_register_back:
			finish();
			break;
		case R.id.btn_getcode:
			if(!AppUtils.stringFileter(reg_phone.getText().toString())){
				AppUtils.showDialog(RegisterActivity.this, "请输入正确的手机号");
			}else{
				if(!AppUtils.isNetworkAvailable(RegisterActivity.this)){
					Toast.makeText(RegisterActivity.this, "无网络连接", Toast.LENGTH_SHORT).show();
				}else{
					TimeCount timeCount = new TimeCount(60000, 1000);
					timeCount.start();
					new Thread(new Runnable() {
						@Override
						public void run() {
							String result = ServerConnection.GetCode(reg_phone.getText().toString());
							if(result.equals("exception")){
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(RegisterActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_SHORT).show();
									}
								});
							}
						}
					}).start();				
				}
			}
			
			break;
		case R.id.user_protocol:
			startActivity(new Intent(RegisterActivity.this, AppPrivacyActivity.class));
			break;
		case R.id.btn_register:
			if(reg_personal.getText().toString().equals("")){
				showDialog(this, "请输入用户名称");
			}else if(reg_phone.getText().toString().equals("")){
				showDialog(this, "请输入手机号");
			}else if(reg_code.getText().toString().equals("")){
				showDialog(this, "请输入验证码");
			}else if(reg_pwd.getText().toString().equals("")){
				showDialog(this, "请输入密码");
			}else if(!AppUtils.isNetworkAvailable(RegisterActivity.this)){
				Toast.makeText(RegisterActivity.this, "无网络连接", Toast.LENGTH_SHORT).show();
			}else{
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						String phone = reg_phone.getText().toString();
						String code = reg_code.getText().toString();
						String pwd = reg_pwd.getText().toString();
						String nick = reg_personal.getText().toString();
						String result = ServerConnection.Register(phone, pwd, code,nick);
						if(result.equals("exception")){
							runOnUiThread(new Runnable() {
								
								@Override
								public void run() {
									Toast.makeText(RegisterActivity.this, "网络异常，请检查网络连接", Toast.LENGTH_SHORT).show();
								}
							});
						}else{
							try {
								JSONObject jsonObject = new JSONObject(result);
								final String getResult = jsonObject.getString("success");
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										if(getResult.equals("true")){
											Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
//											SharedPreferences shared = getSharedPreferences("shared_login", 0);
//											String phone = shared.getString("phone", "0");
//											String usernick = shared.getString("usernick", "0");
//											shared.edit().putString("phone", "").commit();
//											shared.edit().putString("usernick", "").commit();
											startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
											finish();
										}else{
											Toast.makeText(RegisterActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
										}
									}
								});
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						
					}
				}).start();
			}
			break;
		}
	}
	
	//信息提示对话框
	public void showDialog(final Activity context,String message){
		Dialog dialog = new AlertDialog.Builder(context)
        .setTitle("系统提示") 
        .setMessage(message) 
        .setNeutralButton("确定", 
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	dialog.dismiss();
                }
            })
        .setPositiveButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.dismiss();
            }
        }).create();
    dialog.show(); 
	}

	class TimeCount extends CountDownTimer{
		
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}
		
		@Override
		public void onTick(long millisUntilFinished) {
			btn_getcode.setClickable(false);
			btn_getcode.setText(millisUntilFinished/1000+"秒");
		}
		
		@Override
		public void onFinish() {
			btn_getcode.setText("重新发送");
			btn_getcode.setClickable(true);
		}
		
	}
}

